import os
import glob
from mutagen import File
from mutagen.id3 import ID3, TPE1, TIT2
import re

def clean_filename(text):
    """清理文件名中的非法字符"""
    if text is None:
        return ""
    # 移除Windows文件名中不允许的字符
    illegal_chars = r'[<>:"/\\|?*\x00-\x1f]'
    cleaned = re.sub(illegal_chars, '', str(text))
    # 移除首尾空格
    return cleaned.strip()

def get_mp3_metadata(file_path):
    """获取MP3文件的元数据（作者和歌曲名）"""
    try:
        audio = File(file_path, easy=True)
        if audio is None:
            audio = ID3(file_path)
        
        # 尝试获取作者信息
        artist = None
        if 'artist' in audio and audio['artist']:
            artist = audio['artist'][0]
        elif 'TPE1' in audio and audio['TPE1']:
            artist = str(audio['TPE1'])
        
        # 尝试获取歌曲名
        title = None
        if 'title' in audio and audio['title']:
            title = audio['title'][0]
        elif 'TIT2' in audio and audio['TIT2']:
            title = str(audio['TIT2'])
        
        return artist, title
        
    except Exception as e:
        print(f"读取文件 {file_path} 的元数据时出错: {e}")
        return None, None

def rename_mp3_files():
    """批量重命名当前目录下的MP3文件"""
    # 获取当前目录下所有MP3文件
    mp3_files = glob.glob("*.mp3")
    
    if not mp3_files:
        print("当前目录下没有找到MP3文件。")
        return
    
    print(f"找到 {len(mp3_files)} 个MP3文件:")
    
    renamed_count = 0
    skipped_count = 0
    
    for mp3_file in mp3_files:
        print(f"\n处理文件: {mp3_file}")
        
        # 获取元数据
        artist, title = get_mp3_metadata(mp3_file)
        
        if artist and title:
            # 清理作者和歌曲名
            clean_artist = clean_filename(artist)
            clean_title = clean_filename(title)
            
            # 构建新文件名
            new_name = f"{clean_artist} - {clean_title}.mp3"
            
            # 如果新文件名与旧文件名相同，跳过
            if new_name == mp3_file:
                print(f"  文件名已符合格式，跳过: {mp3_file}")
                skipped_count += 1
                continue
            
            # 检查新文件名是否已存在
            if os.path.exists(new_name):
                print(f"  警告: 目标文件已存在，跳过重命名: {new_name}")
                skipped_count += 1
                continue
            
            try:
                # 重命名文件
                os.rename(mp3_file, new_name)
                print(f"  成功重命名为: {new_name}")
                renamed_count += 1
                
            except Exception as e:
                print(f"  重命名失败: {e}")
                skipped_count += 1
                
        else:
            missing_info = []
            if not artist:
                missing_info.append("作者")
            if not title:
                missing_info.append("歌曲名")
            print(f"  跳过 - 缺少元数据: {', '.join(missing_info)}")
            skipped_count += 1
    
    print(f"\n批量重命名完成!")
    print(f"成功重命名: {renamed_count} 个文件")
    print(f"跳过: {skipped_count} 个文件")

def main():
    """主函数"""
    print("MP3批量更名工具")
    print("=" * 40)
    print("此工具将重命名当前目录下的MP3文件为格式: 《作者名》 - 《歌曲名》.mp3")
    print("\n当前目录:", os.getcwd())
    
    # 显示当前目录下的MP3文件
    mp3_files = glob.glob("*.mp3")
    if mp3_files:
        print(f"\n当前目录下的MP3文件 ({len(mp3_files)} 个):")
        for file in mp3_files:
            print(f"  - {file}")
    
    # 确认操作
    confirm = input("\n是否继续重命名? (y/N): ").strip().lower()
    if confirm in ['y', 'yes']:
        rename_mp3_files()
    else:
        print("操作已取消。")

if __name__ == "__main__":
    main()